using System;
using System.Linq;
using SPConf.Models.Repository;
using SubSonic.Repository;

namespace SPConf.Models
{
  public class ConfUsersRepository
  {
    private readonly SimpleRepository _db;

    public ConfUsersRepository()
    {
      _db = SimpleRepositoryFactory.Create();
    }

    public void Add(ConfUser confUser)
    {
      _db.Add(UserProfile.From(confUser));
    }

    public ConfUser GetBy(string userName)
    {
      return UserProfile.From(_db.All<UserProfile>().Single(x => x.Id == userName));
    }

    public void CreateIfNotExist(string userName, string email, string fullName)
    {
      if (_db.All<UserProfile>().Where(x => x.Id == userName).Count() == 0)
        Add(new ConfUser
        {
          Id = userName,
          Email = email,
          FullName = fullName
        });
    }

    public void Update(ConfUser confUser)
    {
      _db.Delete<UserProfile>(confUser.Id);
      Add(confUser);
    }

    public class UserProfile
    {
      public string Id { get; set; }

      public string FullName { get; set; }

      public string Email { get; set; }

      public string Description { get; set; }

      public string Type { get; set; }

      public string Section { get; set; }

      public static UserProfile From(ConfUser confUser)
      {
        return new UserProfile
                 {
                   Id = confUser.Id,
                   Description = confUser.Description ?? string.Empty,
                   Email = confUser.Email ?? string.Empty,
                   FullName = confUser.FullName ?? string.Empty,
                   Section = confUser.Section.ToString(),
                   Type = confUser.Type.ToString()
                 };
      }

      public static ConfUser From(UserProfile profile)
      {
        return new ConfUser
                 {
                   Id = profile.Id,
                   Description = profile.Description,
                   Email = profile.Email,
                   FullName = profile.FullName,
                   Section = (ConfSection)Enum.Parse(typeof(ConfSection), profile.Section),
                   Type = (ConfType)Enum.Parse(typeof(ConfType), profile.Type)
                 };
      }
    }
  }
}